//引入axios
import axios from 'axios'
//引入Elment UI 组件
import {Message} from 'element-ui'
import Loading from "element-ui/packages/loading/src";
//引入env.js
import baseURL from './env'
//封装axios请求

//创建axios实例
const server = axios.create({
    //axios请求基地址
    baseURL: `${baseURL.prod.baseURL}api/private/v1/`,
    timeout: 5000,
});

//添加请求拦截
server.interceptors.request.use(function (config) {
    // console.log('请求拦截:', config)
    if (config.url !== '/login') {
        //获取token传递给请求头
        const token = sessionStorage.getItem('token')
        //配置请求头
        if (token) {
            config.headers['Authorization'] = token
        }
    }
    return config;
}, function (error) {
    //请求报错
    return Promise.reject(error);
});


//请求响应拦截
server.interceptors.response.use(function (response) {
    //成功返回
    const loading = Loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    // console.log('响应拦截：', response)
    const res = response.data;
    const resultOk = [200, 201, 204, 400, 401, 403, 404, 422, 500]
    if (resultOk.includes(res.meta.status)) {
        //轻提示
        Message({
            message: res.meta.msg,
            type: 'success'
        })
        //成功返回
        loading.close()
        return res.data
    }
    return Promise.reject('返回数据有误，请检查');
}, function (error) {
    //失败返回
    return Promise.reject(error);
});


export default server;

